import React, { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Menu, Spin } from "antd";
import { findAllBreadcrumb, getOpenKeys } from "@/utils/util";
import { setMenuList } from "@/redux/modules/menu/action";
import { setBreadcrumbList } from "@/redux/modules/breadcrumb/action";
import { connect } from "react-redux";
import type { MenuProps } from "antd";
import Logo from "./components/Logo";
import getMenus from "@/routers/utils/getMenu";
import "./index.less";

const LayoutMenu = (props: any) => {
	const { pathname } = useLocation();
	const { isCollapse, setBreadcrumbList, setMenuList: setMenuListAction } = props;
	const [selectedKeys, setSelectedKeys] = useState<string[]>([pathname]);
	const [openKeys, setOpenKeys] = useState<string[]>([]);

	// 刷新页面菜单保持高亮
	useEffect(() => {
		setSelectedKeys([pathname]);
		isCollapse ? null : setOpenKeys(getOpenKeys(pathname));
	}, [pathname, isCollapse]);

	// 设置当前展开的 subMenu
	const onOpenChange = (openKeys: string[]) => {
		if (openKeys.length === 0 || openKeys.length === 1) return setOpenKeys(openKeys);
		const latestOpenKey = openKeys[openKeys.length - 1];
		if (latestOpenKey.includes(openKeys[0])) return setOpenKeys(openKeys);
		setOpenKeys([latestOpenKey]);
	};

	// 定义 menu 类型
	type MenuItem = Required<MenuProps>["items"][number];

	// 获取菜单列表并处理成 antd menu 需要的格式
	const [menuList, setMenuList] = useState<MenuItem[]>([]);
	const [menuDict, setMenuDict] = useState({});
	const [loading, setLoading] = useState(false);
	const navigate = useNavigate();
	useEffect(() => {
		setLoading(true);
		try {
			const { menulist: menudata, menudict, breadcrumbdict } = getMenus();
			document.title = menudict[pathname] || "";
			setMenuList(menudata);
			setMenuDict(menudict);
			setBreadcrumbList(breadcrumbdict);
			setMenuListAction(menudata);
		} finally {
			setLoading(false);
		}
	}, []);

	return (
		<div className='menu'>
			<Spin spinning={loading} tip='Loading...'>
				<Logo></Logo>
				<Menu
					className=' bg-transparent text-white'
					mode='inline'
					triggerSubMenuAction='click'
					openKeys={openKeys}
					selectedKeys={selectedKeys}
					items={menuList}
					onClick={({ key }) => {
						navigate(key);
						document.title = menuDict[key];
					}}
					onOpenChange={onOpenChange}></Menu>
			</Spin>
		</div>
	);
};

const mapStateToProps = (state: any) => state.menu;
const mapDispatchToProps = { setMenuList, setBreadcrumbList };
export default connect(mapStateToProps, mapDispatchToProps)(LayoutMenu);
